package com.example.myrecyclerview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myviewHolder>{
    private List<Bean> data;
    private Context context;

    public MyAdapter(List<Bean> data, Context context) {
        this.data = data;
        this.context = context;
    }

    @NonNull
    @Override
    public myviewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view=View.inflate(context,R.layout.recyclerview_item,null);
        return new myviewHolder(view);
    }
//    绑定数据
    @Override
    public void onBindViewHolder(@NonNull myviewHolder holder, int position) {
            holder.tv.setText(data.get(position).getName());
    }
    //显示的item长度
    @Override
    public int getItemCount() {
        return data==null ? 0 : data.size();
    }

    public class myviewHolder extends RecyclerView.ViewHolder{
        private TextView tv;
        public myviewHolder(@NonNull View itemView) {
            super(itemView);
            tv=itemView.findViewById(R.id.tv);
            //点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(onitemClickListener!=null){
                        onitemClickListener.onRecyclerItemclick(getAdapterPosition());
                    }
                }
            });

        }
    }
    private  OnRecyclerItemClickListener onitemClickListener;
    public void setRecyclerItemClickListener(OnRecyclerItemClickListener onitemlistener){
        onitemClickListener=onitemlistener;
    }
    public interface OnRecyclerItemClickListener{
        void onRecyclerItemclick(int position);
    }
}
